import React, { useState, useEffect } from 'react';
import { EditorContent, useEditor } from '@tiptap/react';
import { useEditorConfig } from './utils/useEditorConfig';
import { useEditorState } from './utils/useEditorState';
import { Toolbar } from './Toolbar';
import { EditorProps } from './utils/lxdy';
import { defaultContent } from './utils/cldy';
import HistorySidebar from './HistorySidebar';
import axios from 'axios';
import './Tiptap.css';
import { names, colors } from './utils/cldy'

const API_BASE_URL = 'http://localhost:4334';
import './css.css'

const Editor: React.FC<EditorProps> = ({ ydoc, provider, room }) => {
  const editorConfig = useEditorConfig(ydoc, provider);
  const {
    status,
    setStatus,
    currentUser,
    setCurrentUser,
    projectId,
    setProjectId,
    isEditMode,
    setIsEditMode,
    currentEditId,
    setCurrentEditId,
  } = useEditorState(room, provider);

  const [formatPainter, setFormatPainter] = useState<null | { active: boolean; format: any }>(null);
  const [lists, setlists] = useState([]);

  const editor = useEditor({
    ...editorConfig,
    onCreate: ({ editor }) => {
      provider.on('synced', () => {
        if (editor.isEmpty) {
          editor.commands.setContent(defaultContent);
        }
      });
    },
  });

  // 获取历史记录列表
  const getlist = async () => {
    try {
      const res = await axios.get(`${API_BASE_URL}/getlist`);
      setlists(res.data.data);
    } catch (error) {
      console.error('获取历史记录失败:', error);
    }
  };

  // 保存当前编辑内容
  const saveContent = async () => {
    try {
      const content = editor?.getJSON();
      // 将内容转换为与 decodeContent 对应的编码格式
      const jsonString = JSON.stringify(content);
      const encoder = new TextEncoder();
      const uint8Array = encoder.encode(jsonString);
      const encodedContent = btoa(
        String.fromCharCode.apply(null, Array.from(uint8Array))
      );
      // console.log(encodedContent);

      await axios.post(`${API_BASE_URL}/add`, {
        content: encodedContent,
        timestamp: new Date(),
        room,
      });
      await getlist();
      editor?.commands.setContent(defaultContent);
      setIsEditMode(false);
      setCurrentEditId(null);
    } catch (error) {
      console.error('保存失败:', error);
    }
  };

  const [userList, setUserList] = useState<Array<{ name: string; color: string }>>([]);
  const [onlineUsers, setOnlineUsers] = useState(1);

  useEffect(() => {
    if (!provider) return;

    const randomName = names[Math.floor(Math.random() * names.length)];
    const randomColor = colors[Math.floor(Math.random() * colors.length)];

    provider.awareness?.setLocalStateField('user', {
      name: randomName,
      color: randomColor,
    });

    const updateUsers = () => {
      const states = Array.from(provider.awareness?.getStates()?.values() ?? []);
      const users = states.map(state => state.user).filter(Boolean);
      setOnlineUsers(users.length);
      setUserList(users);
    };

    provider.awareness?.on('change', updateUsers);
    updateUsers();

    provider.disconnect = () => {
      setTimeout(() => {
        provider.connect();
      }, 3000);
    };

    getlist();

    return () => {
      provider.awareness?.off('change', updateUsers);
      provider?.destroy();
    };
  }, [editor, provider]);


  if (!editor) {
    return null;
  }

  // 修改内容的处理函数
  const handleUpdate = async () => {
    try {
      const content = editor?.getJSON();
      const jsonString = JSON.stringify(content);
      const encoder = new TextEncoder();
      const uint8Array = encoder.encode(jsonString);
      const encodedContent = btoa(
        String.fromCharCode.apply(null, Array.from(uint8Array))
      );

      const response = await axios.post(`${API_BASE_URL}/update`, {
        currentEditId,
        content: encodedContent,
        timestamp: new Date(),
        room,
      });

      if (response.data.code === 200) {
        // 更新成功后重置状态
        setIsEditMode(false);
        setCurrentEditId(null);
        editor.commands.setContent(defaultContent);
        await getlist();

        // 重置协作状态
        provider?.awareness?.setLocalStateField('editMode', {
          isEditMode: false,
          currentEditId: null
        });
      }
    } catch (error) {
      console.error('更新失败:', error);
    }
  };

  return (
    <div className="main-container">
      <HistorySidebar
        editor={editor}
        provider={provider}
        lists={lists}
        setIsEditMode={setIsEditMode}
        setCurrentEditId={setCurrentEditId}
        defaultContent={defaultContent}
        currentEditId={currentEditId}
      />
      <div className="editor-container">
        <Toolbar
          editor={editor}
          formatPainter={formatPainter}
          setFormatPainter={setFormatPainter}
        />
        <EditorContent editor={editor} />
        <div className="editor-status">
          <div className="online-users-container">
            <span className="online-count">
              <span className="online-dot"></span>
              {onlineUsers} 人在线
            </span>
            <div className="online-avatars">
              {userList.slice(0, 3).map((user, index) => (
                <div
                  key={index}
                  className="avatar"
                  style={{ backgroundColor: user.color }}
                >
                  {user.name[0]}
                </div>
              ))}
              {userList.length > 3 && (
                <div className="avatar avatar-more">
                  +{userList.length - 3}
                </div>
              )}
            </div>
          </div>
          {isEditMode ? (
            <button onClick={handleUpdate}>修改</button>
          ) : (
            <button onClick={saveContent}>保存</button>
          )}
        </div>
      </div>
    </div>
  );
};

export default Editor;